package com.justreading.order.utils;

import com.justreading.order.config.CosConfig;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

/**
 * @author LYJ
 * @Description
 * @date 2021 年 05 月 09 日 11:10
 */
@Component
public class CosUtil {

    private static final Logger log = LoggerFactory.getLogger(CosConfig.class);

    @Autowired
    private CosConfig cosConfig;

    @Autowired
    private COSClient cosClient;

    //上传文件的文件夹
    private static final String DIRNAME = "uploadFile/";


    /**
     * 向存储桶中添加图片
     * @param multipartFile
     * @return
     */
    public String addResourceIntoBucketUploadFile(MultipartFile multipartFile){
        String filePath = null;
        try{
            String bucketName = cosConfig.getHappyCampusBucket();
            String fileName = UUID.randomUUID().toString().substring(0, 8);
            String originalFilename = multipartFile.getOriginalFilename();
            assert originalFilename != null;
            String suffix = originalFilename.substring(originalFilename.indexOf("."));
            String key = DIRNAME + fileName + suffix;
            File tempFile = File.createTempFile(fileName, suffix);
            multipartFile.transferTo(tempFile);
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, tempFile);
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            filePath = cosConfig.getPathNJ() + key;
        }catch(Exception e){
            log.info("{}文件上传失败",multipartFile.getOriginalFilename());
        }finally{
           cosClient.shutdown();
        }
        return filePath;
    }
}
